package com.hotel.core.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.report.ProcessingMessage;
import com.github.fge.jsonschema.report.ProcessingReport;
import com.github.fge.jsonschema.util.JsonLoader;

import java.io.IOException;

public class JsonValidator {
    private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();

    public static void validator(final String schemaResource, final String jsonData)
            throws IOException, ProcessingException {
        final JsonNode schemaJson = JsonLoader.fromResource(schemaResource);
        final JsonNode dataJson = JsonLoader.fromString(jsonData);

        final JsonSchema schema = factory.getJsonSchema(schemaJson);

        ProcessingReport report = schema.validate(dataJson);

        printReport(report);
    }

    private static void printReport(final ProcessingReport report) {
        final boolean success = report.isSuccess();
        System.out.println("Validation " + (success ? "succeeded" : "failed"));

        if (!success) {
            System.out.println("---- BEGIN REPORT ----");
            for (final ProcessingMessage message : report)
                System.out.println(message);
            System.out.println("---- END REPORT ----");
        }
    }
}
